﻿using Microsoft.Extensions.DependencyInjection.Extensions;
using SimpleX.Cache;

namespace SimpleX
{
    public static partial class ServicesExtension
    {
        public static IServiceCollection AddCache(this IServiceCollection services)
        {
            var cacheSettings = App.Get<CacheSettings>("CacheSettings");

            if (cacheSettings.UseRedis)
            {
                var rs = cacheSettings.RedisSettings;

                //注入NewLife.Caching Redis
                var redis = new NewLife.Caching.FullRedis($"{rs.Host}:{rs.Port}", rs.Password, rs.Db)
                {
                    Timeout = rs.TimeOut
                };

                services.TryAddSingleton<NewLife.Caching.ICache>(redis);
                services.AddSingleton<NewLife.Caching.Redis>(redis);
                services.AddSingleton(redis);

                //注入二次封装的Redis
                services.AddSingleton<ICacheService, RedisCacheService>();
            }
            else
            {
                services.AddSingleton<ICacheService, MemoryCacheService>();
            }

            return services;
        }
    }
}